Skip to content

Two handy extensions to work with HTTPClientResponse body #736

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: main
Choose a base branch
from

Conversation

makoni
Copy link

@makoni makoni commented Apr 8, 2024

Two extensions for HTTPClientResponse to avoid boilerplate code.

Reading a response data currently:

let expectedBytes = headers.first(name: "content-length").flatMap(Int.init) ?? 1024 * 1024
var bytes = try await body.collect(upTo: expectedBytes)
if let data = bytes.readData(length: bytes.readableBytes) {
    // handle data
}

With the extension:

if let data = try await response.data(upTo: 1024*1024) {
    // handle data
}

Additionally an extension for bytes. Currently:

let expectedBytes = headers.first(name: "content-length").flatMap(Int.init) ?? 1024 * 1024
var bytes = try await body.collect(upTo: expectedBytes)

With the extension:

var bytes = try await response.bytes(upTo: 1024*1024)

Copy link
Collaborator

@Lukasa Lukasa left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally these look really good! Can you add a couple of tests for them as well?

@swift-server swift-server deleted a comment from Mizhkaa Apr 9, 2024
@makoni makoni requested a review from Lukasa April 9, 2024 11:25
@makoni makoni requested review from Lukasa and fabianfett August 8, 2025 15:44
@makoni
Copy link
Author

makoni commented Aug 8, 2025

It's been a while but I updated it :)

/// - Parameter maxBytes: The maximum number of bytes this method is allowed to accumulate.
/// - Returns: Bytes collected over time
public func bytes(upTo maxBytes: Int) async throws -> ByteBuffer {
let expectedBytes = self.headers.first(name: "content-length").flatMap(Int.init) ?? maxBytes
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should always use maxBytes and never the value from content-length.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

@makoni makoni requested a review from Lukasa August 15, 2025 15:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants